import 'package:interview/utils/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ThemeSharedPreferencesHelper {
  static const String _themeKey = "userTheme";

  /// 初始化默认主题
  /// 如果未存储主题，则将默认主题设置为 `system`
  static Future<void> initializeTheme() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      if (!prefs.containsKey(_themeKey)) {
        // 默认设置为系统主题
        await prefs.setString(_themeKey, "system");
        Logger.info("默认主题初始化为系统模式", tag: "Theme");
      }
    } catch (e) {
      Logger.error("初始化主题时发生错误: $e", tag: "Theme");
    }
  }

  /// 获取当前存储的主题 返回 `light`, `dark` 或 `system`
  static Future<String> getTheme() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_themeKey) ?? "system"; // 默认返回系统主题
  }

  /// 更新用户的主题 参数 [theme] 只能是 `light`, `dark` 或 `system`
  static Future<void> updateTheme(String theme) async {
    if (theme != "light" && theme != "dark" && theme != "system") {
      Logger.error("无效的主题设置：$theme", tag: "Theme Update");
      return;
    }

    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_themeKey, theme);
      Logger.info("主题更新成功：$theme", tag: "Theme");
    } catch (e) {
      Logger.error("更新主题时发生错误: $e", tag: "Theme");
    }
  }

  /// 清除主题设置（恢复默认值）
  static Future<void> clearTheme() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_themeKey);
    Logger.info("主题设置已清除！", tag: "Theme");
  }
}
